<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="名称" prop="title">
           <el-input
             v-model="queryParams.title"
             placeholder="请输入名称"
             clearable
             style="width: 240px"
             @keyup.enter="handleQuery"
           />
         </el-form-item>
         <el-form-item label="状态" prop="status">
           <el-select
               v-model="queryParams.status"
               placeholder="请选择状态"
               clearable
               style="width: 240px"
           >
             <el-option
                 v-for="dict in dict.type.disabled_state"
                 :key="dict.value"
                 :label="dict.label"
                 :value="dict.value"
             />
           </el-select>
         </el-form-item>
        <!-- <el-form-item label="所属运营商" prop="operatId">
          <el-select style="width: 200px;" v-model="queryParams.operatId" placeholder="请选择">
            <el-option
              v-for="item in operatorOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select>
         </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:billing_rule:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:billing_rule:remove']"
          >删除
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 表格数据 -->
      <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="id" prop="id" width="120"/>
          <el-table-column label="名称" prop="title" :show-overflow-tooltip="true"/>
          <el-table-column label="状态" prop="status" align="center">
            <template slot-scope="{row}">
              <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime">
            <template slot-scope="{row}">
                <span>{{ row.createTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <el-button
               type="text"
               icon="el-icon-document-copy"
               @click="handleCopy(row)"
               v-hasPermi="['system:billing_rule:copy']"></el-button>
              <el-button
               type="text"
               icon="el-icon-edit"
               @click="handleUpdate(row)"
               v-hasPermi="['system:billing_rule:edit']"></el-button>
              <el-button
               type="text"
               icon="el-icon-delete"
               @click="handleDelete(row)"
               v-hasPermi="['system:billing_rule:remove']"></el-button>
            </template>
          </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改计费规则对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="基本配置" name="base_config"></el-tab-pane>
          <el-tab-pane label="时间计价规则" name="time_pricing_rules"></el-tab-pane>
          <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
            <div v-if="activeName == 'base_config'">
              <el-form-item label="名称" prop="title" style="width: 100%;">
                  <el-input v-model="form.title" placeholder="请输入名称"/>
              </el-form-item>
              <!-- <el-form-item label="所属运营商"  prop="operatId">
                  <el-select v-model="form.operatId" style="width: 200px;" placeholder="请选择">
                      <el-option
                          v-for="item in operatorOptions"
                          :key="item.id"
                          :label="item.label"
                          :value="parseInt(item.id)"
                      ></el-option>
                  </el-select>
              </el-form-item> -->
              <el-form-item label="状态" style="width: 100%;" prop="status">
                  <el-radio-group v-model="form.status">
                      <el-radio
                          v-for="dict in dict.type.disabled_state"
                          :key="dict.value"
                          :label="Number(dict.value)"
                      >{{ dict.label }}
                      </el-radio>
                  </el-radio-group>
              </el-form-item>
              <el-form-item label="延迟费" prop="delayPrice">
                  <el-input v-model="form.delayPrice" placeholder="请输入延迟费"/>
              </el-form-item>
              <el-form-item label="计损电量" prop="lossRatio">
                  <el-input v-model="form.lossRatio" placeholder="请输入计损电量"/>
              </el-form-item>
              <el-form-item label="尖费率" prop="sharpRate">
                  <el-input v-model="form.sharpRate" placeholder="请输入尖费率"/>
              </el-form-item>
              <el-form-item label="尖服务费" prop="sharpService">
                  <el-input v-model="form.sharpService" placeholder="请输入尖服务费"/>
              </el-form-item>
              <el-form-item label="峰费率" prop="peakRate">
                  <el-input v-model="form.peakRate" placeholder="请输入峰费率"/>
              </el-form-item>
              <el-form-item label="峰服务费" prop="peakService">
                  <el-input v-model="form.peakService" placeholder="请输入峰服务费"/>
              </el-form-item>
              <el-form-item label="平费率" prop="flatRate">
                  <el-input v-model="form.flatRate" placeholder="请输入平费率"/>
              </el-form-item>
              <el-form-item label="平服务费" prop="flatService">
                  <el-input v-model="form.flatService" placeholder="请输入平服务费"/>
              </el-form-item>
              <el-form-item label="谷费率" prop="valleyRate">
                  <el-input v-model="form.valleyRate" placeholder="请输入谷费率"/>
              </el-form-item>
              <el-form-item label="谷服务费" prop="valleyService">
                  <el-input v-model="form.valleyService" placeholder="请输入谷服务费"/>
              </el-form-item>
            </div>
            <el-row v-if="form.periodPriceList.length && activeName == 'time_pricing_rules'">
             <div v-for="(rule, index) in form.periodPriceList" :key="index" style="width: 100%;display: flex;">
               <el-col :span="12">
                 <el-form-item label="时间段" style="width: 100%;" label-width="90">
                   <div style="width: 100%;display: flex;">
                     <el-time-select
                       key="time1"
                       style="width: 160px;"
                       placeholder="开始时间"
                       v-model="rule.start"
                       :picker-options="{
                         start: '00:00',
                         step: '00:30',
                         end: '24:00'
                       }">
                     </el-time-select>
                     <div style="margin: 0 5px;">-</div>
                     <el-time-select
                     style="width: 160px;"
                     key="time2"
                     placeholder="结束时间"
                     v-model="rule.end"
                     :picker-options="{
                       start: '00:00',
                       step: '00:30',
                       end: '24:00'
                     }">
                     </el-time-select>
                   </div>
                 </el-form-item>
               </el-col>
               <el-col :span="12">
                 <el-form-item label="价格(元/Kwh)" style="width: 100%;" label-width="100">
                   <div style="width: 100%;display: flex;">
                     <el-select v-model="rule.type" class="m-2" placeholder="请选择" >
                         <el-option v-for="item in timePriceRuleOptions" :key="item.value" :value="item.value" :label="item.label" />
                     </el-select>
                     <div style="display: flex;margin-left:10px;">
                       <el-button @click="addList">+</el-button>
                       <el-button v-if="form.periodPriceList.length > 1" @click="removeList">-</el-button>
                     </div>
                   </div>
                 </el-form-item>
               </el-col>

             </div>

            </el-row>


        </el-form>


        </el-tabs>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import {
    EXPORT_URL,
    addRule,
    getAllOperator,
    copyRule,
    delRule,
    getRule,
    listRule,
    updateRule,
		changeStatus
} from "@/api/station/billing_rules";
export default {
  name: "Billing_rules",
  dicts: ['disabled_state'],
  components: {  },
  data() {
    return {
      activeName:'base_config',
      form: {periodPriceList:[{}]},// 表单参数
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      queryParams: {// 查询参数
        pageNum: 1,
        pageSize: 10,
        status: null,
        title:'',
      },
      // 总条数
      total: 0,
      rules: {
        title: [{required: true, message: "名称不能为空", trigger: "blur"}],
        operatId: [{required: true, message: "请选择所属运营商", trigger: "blur"}],
        delayPrice: [{required: true, message: "延迟费不能为空", trigger: "blur"}],
        status: [{required: true, message: "请选择状态", trigger: "blur"}]
      },
      operatorOptions:[],//所属运营商
      list:[],//页面数据
      timePriceRuleOptions:[//价格(元/Kwh)
          {value: 0, label: '尖费率'},
          {value: 1, label: '峰费率'},
          {value: 2, label: '平费率'},
          {value: 3, label: '谷费率'},
      ],
    };
  },
  created() {
    this.getList()
    this.getOperators()
  },
  methods: {
    getList() {
      this.loading = true;
      listRule(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.list = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      });
    },
    addList(){//时间计价规则新增
    	this.form['periodPriceList'].push({start: '',end: '', type: ''})
    },
    removeList(index){//时间计价规则删除
    	this.form['periodPriceList'].splice(index,1)
    },
    handleChange(index, value) {
      this.timePricingRules[index] = value;
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.open = true;
      this.getOperators();
      this.reset();
      this.title = "添加计费规则";
    },
    handleUpdate(row) {
      this.getOperators();
      this.reset();
      const id = row.id || this.ids;
      this.open = true;
      this.title = "修改计费规则";
      getRule(id).then(response => {
        let periodPriceList = [
          {start: '',end: '', type: ''},
        ]
        let data = response.data || {}
        this.form = {...data,periodPriceList:data.periodPriceList || periodPriceList};
      });
    },
    getOperators() {
      getAllOperator().then(resp => {
        this.operatorOptions = resp.data || []
      })
    },
    // 表单重置
    reset() {
      this.form = {periodPriceList:[{}]};
      this.resetForm("formRef");
    },
    timeBijiao(time1,time2){
    	if(!time1 || !time2) return false
    	let time1List = time1.split(':')
    	let time2List = time2.split(':')
    	return (Number(time1List[0]) > Number(time2List[0])) || ( time1List[0] == time2List[0] &&  Number(time1List[1]) > Number(time2List[1]) )
    },
    isNull(str){
    	return str === undefined || str === null || str === ''
    },
    submitForm() {
      this.$refs["formRef"].validate(valid => {
        if (valid) {
          let periodPriceList = this.form['periodPriceList'] || []
          if(periodPriceList[periodPriceList.length-1].end == '00:00') periodPriceList[periodPriceList.length-1].end = '24:00'
          let flag = ''
          periodPriceList.map((item,index)=>{
            if(this.isNull(item.type) || this.isNull(item.start) || this.isNull(item.end)) {
              flag = '请填写完整的规则'
            }else if(
            index > 0 && index < (periodPriceList.length - 1)
            && (this.timeBijiao(periodPriceList[index-1].end,periodPriceList[index].start)
            || this.timeBijiao(periodPriceList[index].end,periodPriceList[index + 1].start)
            ) ){
              flag = '请填写正确的时间段'
            }else if( this.timeBijiao(periodPriceList[index].start,periodPriceList[index].end) ) {
              flag = '请填写正确的时间段'
            }
          })
          let forms = {...this.form}
          forms.periodPriceList = [...periodPriceList]
          if(flag) return this.$modal.msgWarning(flag);
          if (this.form.id != undefined) {
            updateRule(forms).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false;
              this.getList();
            });
          } else {
            addRule(forms).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    handleDelete(row) {//删除
      const del_ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + del_ids + '"的数据项？').then(function() {
        return delRule(del_ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleCopy(row) {// 复制
      const id = row.id;
      copyRule(id).then(response => {
        this.getList();
        this.$modal.msgSuccess("复制成功");
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleStatusChange(row) {
        let new_status;
        let text;
        if (row.status == '0') {
            text = '停用';
            new_status = 0;
        } else {
            text = '启用';
            new_status = 1;
        }
        this.$modal.confirm('确认要' + text + '吗?').then(function () {
            // return changeStatus(row.id, row.status);
            return changeStatus({id: row.id, status: new_status});
        }).then(() => {
            this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
            row.status = new_status == 0 ? 1 : 0;
        });
    },
  }
};
</script>
